import datetime
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models

class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None



class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        """ 如果用户已登录 则 request 中赋值   """
        request.tracer = Tracer()
        user_id = request.session.get('user_id',0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object
        #  检查用户是否已经登录，已经登录继续往后走， 未登录返回登录页面
        #  白名单  没有登录都可以访问的url

        #   request.path_info 获取当前正在访问的 url
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return

        if not request.tracer.user:
            return redirect('login')
        #  登录成功后，访问后台管理时 ，获取当前用户所拥有的额度

        #  方式一，  免费额度在交易记录中存储
        #  获取当前用户ID最大值，
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        #
        # 判断是否过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            models.Transaction.objects.filter(user=user_object,status=2,price_policy__category=1).first()

        request.tracer.price_policy = _object.price_policy

        """
        
         # 方式二
        # 获取当前用户id 最大值（最大交易记录）
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        if not _object:
            # 没有购买
            request.price_policy = models.PricePolicy.objects.filter(category=1,title="个人免费版").first()
        else:
            # 付费版
            current_datetime = datetime.datetime.now()
            if  _object.end_datetime and _object.end_datetime <current_datetime:
                request.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
            else:
                request.price_policy = _object.price_policy
                

        """


    def process_view(self,request,view,args,kwargs):
        if not request.path_info.startswith('/manage/'):
            return

        project_id = kwargs.get('project_id')
        #  是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            request.tracer.project = project_object
            #  是我创建的就让他通过
            return
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user,project_id=project_id).first()

        if project_user_object:
            #  是我参与的项目
            request.tracer.project = project_user_object
            return
        return redirect('project_list')















